package cn.itcast.bos.system.security;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.security.Permission;
import cn.itcast.bos.domain.security.Role;
import cn.itcast.bos.domain.security.User;
import cn.itcast.bos.system.dao.UserDao;
import cn.itcast.bos.system.service.PermissionService;
import cn.itcast.bos.system.service.RoleService;
import cn.itcast.bos.system.service.UserService;
//@Service("myrealm")
public class MyRealm extends AuthorizingRealm{
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	private Logger logger=LoggerFactory.getLogger(getClass());
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		logger.info("用户授权管理");
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		Subject subject = SecurityUtils.getSubject();
		User user=(User) subject.getPrincipal();
		List<Role> roles=roleService.getRolesByUserId(user.getId());
		for (Role role : roles) {
			simpleAuthorizationInfo.addRole(role.getKeyword());
		}
		List<Permission> permissions=permissionService.getPermissionByUserId(user.getId());
		for (Permission permission : permissions) {
			simpleAuthorizationInfo.addStringPermission(permission.getKeyword());
		}
		return simpleAuthorizationInfo;
	}

	
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userNamePasswordToken=(UsernamePasswordToken) token;
		User user = userService.findByUsername(userNamePasswordToken.getUsername());
		logger.info(user.getPassword());
		char[] password = userNamePasswordToken.getPassword();
		logger.info(password.toString());
		if(user==null){
			return null;
		}else{
			ByteSource salt = ByteSource.Util.bytes(user.getSalt());
			return new SimpleAuthenticationInfo(user,user.getPassword(),salt,getName());
		}
	}

}
